<template>
  <div class="app-container">
    <el-form :model="formData" size="small" :inline="true" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="询价单编号:" prop="enquiryCode">
            <span>{{ formData.enquiryCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="询价单名称:" prop="enquiryName">
            <span>{{ formData.enquiryName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据日期:" prop="enquiryDate">
            <span>{{ parseTime(formData.enquiryDate, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="询价截止时间:" prop="enquiryDeadline">
            <span>{{ parseTime(formData.enquiryDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="采购人:" prop="buyer">
            <span>{{ formData.buyer }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电话:" prop="buyerPhone">
            <span>{{ formData.buyerPhone }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货地址:" prop="receivingAddress">
            <span>{{ formData.receivingAddress }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div style="font-size: 21px;">报价单列表</div>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cg:enquiry:quotation']"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="quotationList">
      <el-table-column label="报价单编号" align="center" prop="quotationCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
          >{{ scope.row.quotationCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="供应商编码" align="center" prop="vendorCode"/>
      <el-table-column label="供应商名称" align="center" prop="vendorName"/>
      <el-table-column label="报价时间" align="center" prop="quotationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.quotationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交货日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '0'">报价中</span>
          <span v-if="scope.row.status === '1'">报价完成</span>
        </template>
      </el-table-column>
      <el-table-column label="代理人" align="center" prop="agentUserName"/>
      <el-table-column label="含税金额" align="center" prop="taxAmount"/>
      <el-table-column label="不含税金额" align="center" prop="noTaxAmount"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status === '0'"
            v-hasPermi="['cg:enquiry:quotation']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status === '0'"
            v-hasPermi="['cg:enquiry:quotation']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购管理-报价单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="95%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="报价单编号" prop="quotationCode">
            <el-input v-model="form.quotationCode" placeholder="请输入报价单编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="询价单编号" prop="enquiryCode">
            <el-input v-model="form.enquiryCode" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="询价截止时间" prop="enquiryDeadline">
            <el-date-picker clearable
                            v-model="form.enquiryDeadline"
                            type="datetime"
                            value-format="yyyy-MM-dd hh:mm:ss"
                            style="width: 100%;"
                            readonly>
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商" prop="vendorName">
            <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
              <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
            </el-input>
            <VendorSelectAll ref="vendorSelectAll" @onSelected="onVendorSelected" v-if="formData.enquiryRange==='0'"/>
            <VendorSelectRange ref="vendorSelectRange" @onSelected="onVendorSelected" :enquiryId="formData.id" v-if="formData.enquiryRange==='1'"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商联系人" prop="contact">
            <el-input v-model="form.contact" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="contactTel">
            <el-input v-model="form.contactTel" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="代理人" prop="agentUserName">
            <el-input v-model="form.agentUserName" placeholder="请选择代理人" readonly>
              <el-button
                slot="append"
                @click="handleSelectUser"
                icon="el-icon-search">
              </el-button>
            </el-input>
            <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker clearable
                            v-model="form.deliveryDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择交货日期"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <div style="font-size: 21px;">报价明细</div>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini"
                       :disabled="multiple"
                       @click="handleBatch">批量操作
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              action="#"
              ref="upload"
              class="upload-demo"
              accept=".xlsx,.xls"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleImport">
              <template >
                <el-button type="primary" size="mini">导入</el-button>
              </template>
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="handleExport">
              导出
            </el-button>
          </el-col>
        </el-row>
        <el-table border :data="cgPurchaseQuotationLineList" ref="cgPurchaseQuotationLine" height="500"
                  show-summary :summary-method="getSummaries"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" width="50"/>
          <el-table-column label="物料编号" align="center" prop="itemCode" width="150"/>
          <el-table-column label="物料名称"align="center" prop="itemName" width="150"/>
          <el-table-column label="规格型号" align="center" prop="specification" width="150"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure" width="150"/>
          <el-table-column label="需求数量" align="center" prop="quantity" width="150"/>
          <el-table-column label="供货数量" align="center" prop="supplyQuantity" width="150">
            <template slot-scope="scope">
              <el-input-number class="item__input" v-model="scope.row.supplyQuantity" placeholder="请输入供货数量"
                               size="mini" style="width:100%"
                               :min="0"
                               :max="999999999"
                               :precision="2"
                               controls-position="right"
                               :disabled="scope.row.isQuotation==='N'"
                               @change="handleEdit(scope.$index, scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="含税单价" align="center" prop="taxPrice" width="150">
            <template slot-scope="scope">
              <el-input-number class="item__input" v-model="scope.row.taxPrice" placeholder="请输入含税单价"
                               size="mini" style="width:100%"
                               :min="0"
                               :max="1000000"
                               :precision="7"
                               controls-position="right"
                               @change="handleEdit(scope.$index, scope.row)"
                               :disabled="scope.row.isQuotation==='N'"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="税率" align="center" prop="tax" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.tax" placeholder="请选择税率"
                         style="width:100%" :disabled="scope.row.isQuotation==='N'"
              @change="handleEdit(scope.$index, scope.row)">
                <el-option v-for="item in taxRateList" :key="item.taxRate" :value="item.taxRate" :label="item.taxRate">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="不含税单价" align="center" prop="noTaxPrice" width="150"/>
          <el-table-column label="含税金额" align="center" prop="taxAmount" width="150"/>
          <el-table-column label="不含税金额" align="center" prop="noTaxAmount" width="150"/>
          <el-table-column label="是否报价" align="center" prop="isQuotation" width="150" fixed="right">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.isQuotation" label="Y">是</el-radio>
              <el-radio v-model="scope.row.isQuotation" label="N">否</el-radio>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    批量操作弹框-->
    <el-dialog title="批量操作" :visible.sync="batchOpen" width="30%" append-to-body>
      <el-form ref="batchForm" :model="batchForm" label-width="120px">
        <el-form-item label="是否报价">
          <el-radio v-model="batchForm.isQuotation" label="Y">是</el-radio>
          <el-radio v-model="batchForm.isQuotation" label="N">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmBatch">确 定</el-button>
        <el-button @click="batchOpen=false">取 消</el-button>
      </div>
    </el-dialog>
    <QuotationInfoView ref="quotationInfoView"></QuotationInfoView>
  </div>
</template>

<script>
import {listQuotation, getQuotation, delQuotation, addQuotation, updateQuotation,listEnquiryLine,character} from "@/api/mes/cg/quotation";
import VendorSelectAll from "@/components/vendorSelect/single.vue";
import VendorSelectRange from "@/views/mes/cg/quotation/vendorSelectRange.vue";
import {getUserProfile} from "@/api/system/user";
import UserSelect from "@/components/userSelect/single.vue";
import {genCode} from "@/api/system/autocode/rule"
import {getTaxRateSelectData} from "@/api/mes/cg/invoice";
import * as xlsx from "xlsx";
import QuotationInfoView from "@/views/mes/cg/quotation/infoView.vue";
export default {
  name: "Quotation",
  components: {UserSelect, VendorSelectAll,VendorSelectRange,QuotationInfoView},
  data() {
    return {
      // 遮罩层
      loading: true,
      multiple:true,
      itemCodes:[],
      // 子表选中数据
      checkedCgPurchaseQuotationLine: [],
      // 总条数
      total: 0,
      // 采购管理-报价单表格数据
      quotationList: [],
      // 采购管理-采购报价明细表格数据
      cgPurchaseQuotationLineList: [],
      taxRateList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      batchOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enquiryId: null,
        enquiryCode: null
      },
      // 表单参数
      form: {},
      batchForm:{
        isQuotation:null
      },
      // 表单校验
      rules: {
        quotationCode: [
          {required: true, message: "报价单编号不能为空", trigger: "blur"}
        ],
        vendorName:  [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ],
        deliveryDate:  [
          {required: true, message: "交货日期不能为空", trigger: "blur"}
        ],
        agentUserName: [
          {required: true, message: "代理人不能为空", trigger: "blur"}
        ],
        contact:  [
          {required: true, message: "供应商联系人不能为空", trigger: "blur"}
        ],
        contactTel: [
          {required: true, message: "供应商联系电话不能为空", trigger: "blur"}
        ],
      },
      formData: {},
      user: {},
    };
  },
  created() {
    this.formData = this.$route.params;
    this.queryParams.enquiryId = this.formData.id;
    this.queryParams.enquiryCode = this.formData.enquiryCode;
    this.getList();
    this.getUser();
  },
  methods: {
    /** 查询采购管理-报价单列表 */
    getList() {
      this.loading = true;
      listQuotation(this.queryParams).then(response => {
        this.quotationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        quotationCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        contact: null,
        contactTel: null,
        enquiryId: this.formData.id,
        enquiryCode: this.formData.enquiryCode,
        enquiryDeadline: this.formData.enquiryDeadline,
        deliveryDate: new Date().toISOString().split('T')[0],
        agentUserId: this.user.userId,
        agentUserName: this.user.nickName,
        status: "0",
        taxAmount: null,
        noTaxAmount: null
      };
      this.cgPurchaseQuotationLineList = [];
      this.getRaxRateSelectData();
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      listEnquiryLine(this.formData.id).then(response=>{
        this.cgPurchaseQuotationLineList = response.data;
      })
      this.open = true;
      this.handleAutoGenChange();
      this.title = "新增报价";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getQuotation(id).then(response => {
        this.form = response.data;
        this.cgPurchaseQuotationLineList = response.data.cgPurchaseQuotationLineList;
        this.open = true;
        this.title = "修改报价";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for(let i=0;i<this.cgPurchaseQuotationLineList.length;i++){
            const line = this.cgPurchaseQuotationLineList[i];
            if(line.isQuotation==='Y'){
              if(!line.supplyQuantity && line.supplyQuantity<=0){
                this.$modal.msgError("请填写报价商品的供货数量");
                return ;
              }
              if(!line.taxPrice && line.taxPrice<=0){
                this.$modal.msgError("请填写报价商品的价格");
                return ;
              }
              if(!line.tax){
                this.$modal.msgError("请选择报价商品税率");
                return ;
              }
            }
          }
          this.form.cgPurchaseQuotationLineList = this.cgPurchaseQuotationLineList;
          if (this.form.id != null) {
            updateQuotation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuotation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id
      this.$modal.confirm('是否确认删除采购管理-报价单编号为"' + ids + '"的数据项？').then(function () {
        return delQuotation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 采购管理-采购报价明细添加按钮操作 */
    handleImport(event) {
      const file = event.raw;
      const reader=new FileReader();
      reader.onload=(e)=>{
        const data= new Uint8Array(e.target.result);
        const workbook= xlsx.read(data,{type:'array'});
        const worksheet=workbook.Sheets[workbook.SheetNames[0]];
        const jsonData=xlsx.utils.sheet_to_json(worksheet,{header:1});
        //表头数据
        let headers=jsonData[0];
        let array=[];
        jsonData.splice(1).forEach(row=>{
          const rowData=row.reduce((accumulator,item,index)=> {
            let key=headers[index];
            let v=character[key];
            if(v){
              let column=v.column;
              let type=v.type;
              if(type==='number' && item){
                accumulator[column]=Number(item);
              }else{
                accumulator[column]=item;
              }
            }
            return accumulator;

          },{})
          array.push(rowData);
        })
        //对比列表数据编辑导入数据填充列表
        this.cgPurchaseQuotationLineList.forEach( lineItem=>{
          const item=array.find(item =>
          lineItem.itemCode===item.itemCode
          )
          if(item){
            lineItem.supplyQuantity=item.supplyQuantity;
            lineItem.taxPrice=item.taxPrice;
            lineItem.tax=item.tax;
            lineItem.noTaxPrice=parseFloat(item.noTaxPrice).toFixed(7);
            lineItem.taxAmount=parseFloat(item.taxAmount).toFixed(2);
            lineItem.noTaxAmount=parseFloat(item.noTaxAmount).toFixed(2);
            lineItem.isQuotation=item.isQuotation;
          }else{
            lineItem.isQuotation='N';
          }
        })
      }
      reader.readAsArrayBuffer(file);
    },
    /** 导出 */
    handleExport() {
      //定义导出表格表头
      const headers=[['物料编号','物料名称','规格型号','单位','需求数量','供货数量','含税单价','税率','不含税单价','含税金额','不含税金额','是否报价']];
      //定义导出数据属性名称
      const headerOrder = ['itemCode', 'itemName', 'specification', 'unitOfMeasure', 'quantity', 'supplyQuantity', 'taxPrice', 'tax', 'noTaxPrice', 'taxAmount', 'noTaxAmount', 'isQuotation'];
      const data = this.cgPurchaseQuotationLineList.map(item => headerOrder.map(key => item[key]));
      console.log(data);
      // 合并表头和数据
      const worksheetData = headers.concat(data);

      // 创建工作表
      const ws = xlsx.utils.aoa_to_sheet(worksheetData);

      const wb = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(wb, ws, '数据列表');
      xlsx.writeFile(wb, '数据列表.xlsx');
    },
    //供应商选择
    handleSelectVendor() {
      if(this.formData.enquiryRange==='0'){
        this.$refs.vendorSelectAll.showFlag = true;
      }else if(this.formData.enquiryRange==='1'){
        this.$refs.vendorSelectRange.showFlag = true;
      }else {
        this.$modal.msgError("请选择询价单范围");
      }

    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        if (obj.contact1 != null && obj.contact1Tel != null) {
          this.form.contact = obj.contact1;
          this.form.contactTel = obj.contact1Tel;
        } else {
          this.form.contact = obj.contact2;
          this.form.contactTel = obj.contact2Tel;
        }
      }
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.agentUserId = obj.userId;
        this.form.agentUserName = obj.nickName;

      }
    },
    //自动生成编码
    handleAutoGenChange() {
      genCode('CG_QUOTATION_CODE').then(response => {
        this.form.quotationCode = response;
      });
    },
    //获取税率
    getRaxRateSelectData(){
      const query={
        isOpen:0,
        taxType:'进项税'
      }
      getTaxRateSelectData(query).then(response => {
        this.taxRateList = response.data;
      })
    },
    handleEdit(index, row){
      if(row.supplyQuantity && row.taxPrice && row.tax){
        const supplyQuantity = Number(row.supplyQuantity)*100;
        const taxPrice=Number(row.taxPrice)*10000000;
        const taxRage=Number(row.tax)+100;
        row.taxAmount = parseFloat((supplyQuantity*taxPrice)/1000000000).toFixed(2);
        const noTaxPrice=parseInt(taxPrice*100/taxRage);
        row.noTaxAmount = parseFloat((supplyQuantity*noTaxPrice)/1000000000).toFixed(2);
        row.noTaxPrice = parseFloat(noTaxPrice/10000000).toFixed(7);
      }else if(row.supplyQuantity && row.taxPrice){
        const supplyQuantity = Number(row.supplyQuantity)*100;
        const taxPrice=Number(row.taxPrice)*10000000;
        row.taxAmount = parseFloat((supplyQuantity*taxPrice)/1000000000).toFixed(2);
      }else if(row.taxPrice && row.tax){
        const taxPrice=Number(row.taxPrice)*10000000;
        const taxRage=Number(row.tax)+100;
        const noTaxPrice=parseInt(taxPrice*100/taxRage);
        row.noTaxPrice = parseFloat(noTaxPrice/10000000).toFixed(7);
      }
    },
    handleBatch(){
      this.batchForm.isQuotation=null;
      this.batchOpen=true;
    },
    confirmBatch(){
      //批量处理报价明细是否报价属性值
      this.cgPurchaseQuotationLineList=this.cgPurchaseQuotationLineList.map(item=>{
        if(this.itemCodes.includes(item.itemCode)){
          item.isQuotation=this.batchForm.isQuotation;
        }
        return item;
      });
      this.batchOpen=false;
    },
    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      let taxAmountIndexNum = 0;
      let noTaxAmountIndexNum = 0;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data
          .filter(item => item.isQuotation === 'Y') // 过滤掉不参与计算的行
          .map(item => Number(item[column.property]));
        if (column.property === "taxAmount") {
          taxAmountIndexNum = index;
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr*100;
            } else {
              return prev;
            }
          }, 0);
          sums[index]=parseFloat(Number(sums[index])/100).toFixed(2);
          this.form.taxAmount = sums[taxAmountIndexNum];
          sums[index]+=' 元'
        } else if(column.property === "noTaxAmount"){
          noTaxAmountIndexNum = index;
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr*100;
            } else {
              return prev;
            }
          }, 0);
          sums[index]=parseFloat(Number(sums[index])/100).toFixed(2);
          this.form.noTaxAmount = sums[noTaxAmountIndexNum];
          sums[index]+=' 元'
        }else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.itemCodes = selection.map(item => item.itemCode)
      this.multiple = !selection.length
    },
    handleView(row){
      this.$refs.quotationInfoView.init(row.id)
    }
  },
};
</script>
